package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.validator.QueryHelpMybatisPlus;
import cn.cdeden.knowledge.domain.dto.TeamToEnterprise;
import cn.cdeden.knowledge.domain.dto.TeamToEnterpriseDto;
import cn.cdeden.knowledge.domain.dto.TeamToEnterpriseQueryParam;
import cn.cdeden.knowledge.enums.TreeTypeEnum;
import cn.cdeden.knowledge.mapper.TeamToEnterpriseMapper;
import cn.cdeden.knowledge.service.TeamToEnterpriseService;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.resource.api.domain.RemoteFile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author GW
 * @date 2023-04-12
 */
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = TeamToEnterpriseService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TeamToEnterpriseServiceImpl extends ServiceImpl<TeamToEnterpriseMapper, TeamToEnterprise> implements TeamToEnterpriseService {

    // private final RedisUtils redisUtils;
    private final TeamToEnterpriseMapper teamToEnterpriseMapper;

    @Override
    public TableDataInfo<TeamToEnterpriseDto> queryAll(TeamToEnterpriseQueryParam query, Pageable pageable) {
        IPage<TeamToEnterprise> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<TeamToEnterprise> page = teamToEnterpriseMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        TableDataInfo<TeamToEnterprise> build = TableDataInfo.build(page);
        return MapstructUtils.convertTableDataInfo(build, TeamToEnterpriseDto.class);
    }

    @Override
    public List<TeamToEnterpriseDto> queryAll(TeamToEnterpriseQueryParam query) {
        return MapstructUtils.convert(teamToEnterpriseMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), TeamToEnterpriseDto.class);
    }

    @Override
    public TeamToEnterprise getById(Long id) {
        return teamToEnterpriseMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public TeamToEnterpriseDto findById(Long id) {
        return MapstructUtils.convert(getById(id), TeamToEnterpriseDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(TeamToEnterpriseDto resources) {
        TeamToEnterprise entity = MapstructUtils.convert(resources, TeamToEnterprise.class);
        Boolean flag = this.save(entity);
        resources.setId(entity.getId());
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TeamToEnterpriseDto insertFolder(TeamToEnterpriseDto resources) {
        TeamToEnterprise entity = MapstructUtils.convert(resources, TeamToEnterprise.class);
        entity.setType(TreeTypeEnum.FOLDER.getType());
        Boolean flag = this.save(entity);
        resources.setId(entity.getId());
        return resources;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(TeamToEnterpriseDto resources) {
        TeamToEnterprise entity = MapstructUtils.convert(resources, TeamToEnterprise.class);
        boolean ret = this.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(Set<Long> ids) {
        // delCaches(ids);
        return this.removeByIds(ids);
    }

    @Override
    public TeamToEnterpriseDto selectTempTree(String tempTreeId) {
        //获取当前tempTree
        TeamToEnterprise teamToEnterprise = getById(tempTreeId);
        TeamToEnterpriseDto teamToEnterpriseDto = MapstructUtils.convert(teamToEnterprise, TeamToEnterpriseDto.class);
        //获取下级并添加到子节点里
        List<TeamToEnterpriseDto> childrenTreeList = new ArrayList<>();
        List<TeamToEnterpriseDto> childrenTree = getTreeByParentId(tempTreeId);

        //循环添加下级
        for (TeamToEnterpriseDto toEnterprise : childrenTree) {
            childrenTreeList.add(selectTempTree(String.valueOf(toEnterprise.getId())));
        }
        //将添加好的子数据放到属性中
        teamToEnterpriseDto.setChildren(childrenTreeList);
        return teamToEnterpriseDto;
    }

    private List<TeamToEnterpriseDto> getTreeByParentId(String tempTreeId) {
        QueryWrapper<TeamToEnterprise> queryWrapper = new QueryWrapper<TeamToEnterprise>()
                .eq("parent_id", tempTreeId).isNull("delete_id")
                .orderByDesc("create_time")
//                .orderBy(true,true,"type")
                ;
        return MapstructUtils.convert(this.list(queryWrapper), TeamToEnterpriseDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id) {
        Set<Long> set = new HashSet<>(1);
        set.add(id);
        return this.deleteByIds(set);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TeamToEnterpriseDto createFolderFilePath(String parentId, String path) {
        String[] split = path.split("/");
        TeamToEnterpriseDto  tree = null;
        for (String folderName : split) {
            TeamToEnterpriseDto teamToEnterpriseDto = new TeamToEnterpriseDto();
            teamToEnterpriseDto.setParentId(parentId);
            teamToEnterpriseDto.setRealName(folderName);
            tree = insertFolder(teamToEnterpriseDto);
            parentId = String.valueOf(tree.getId());
        }
        return tree;
    }

    @Override
    public TeamToEnterpriseDto createByStorage(String formId, String parentId, RemoteFile remoteFile) {
        TeamToEnterpriseDto teamToEnterpriseDto = new TeamToEnterpriseDto();
        teamToEnterpriseDto.setType(TreeTypeEnum.FILE.getType());
        teamToEnterpriseDto.setParentId(parentId);
        teamToEnterpriseDto.setWflowId(formId);
        teamToEnterpriseDto.setStorageId(remoteFile.getOssId().toString());
        teamToEnterpriseDto.setRealName(remoteFile.getName());
        teamToEnterpriseDto.setSuffix(remoteFile.getFileSuffix());
        teamToEnterpriseDto.setEdition(remoteFile.getVersionId());
        teamToEnterpriseDto.setSize(remoteFile.getFileSize());
//        teamToEnterpriseDto.setFileMd5(remoteFile.());
        insert(teamToEnterpriseDto);
        return teamToEnterpriseDto;
    }

    /*
    private void delCaches(Long id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Long> ids) {
        for (Long id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<TeamToEnterpriseDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (TeamToEnterpriseDto teamToEnterprise : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("父亲编号", teamToEnterprise.getParentId());
              map.put("文件编号", teamToEnterprise.getFileId());
              map.put("后缀名", teamToEnterprise.getSuffix());
              map.put("名称", teamToEnterprise.getRealName());
              map.put("上级路径", teamToEnterprise.getSuperiorsPath());
              map.put("路径", teamToEnterprise.getPath());
              map.put("类型", teamToEnterprise.getType());
              map.put("储存表id", teamToEnterprise.getStorageId());
              map.put("储存服务器类型", teamToEnterprise.getStorageType());
              map.put("文件大小", teamToEnterprise.getSize());
              map.put("关连状态", teamToEnterprise.getLinkingState());
                map.put(" attention",  teamToEnterprise.getAttention());
                map.put(" collection",  teamToEnterprise.getCollection());
                map.put(" isLock",  teamToEnterprise.getIsLock());
                map.put(" columnType",  teamToEnterprise.getColumnType());
              map.put("创建编号", teamToEnterprise.getCreateId());
              map.put("创建者", teamToEnterprise.getCreateBy());
              map.put("创建日期", teamToEnterprise.getCreateTime());
              map.put("更新编号", teamToEnterprise.getUpdateId());
              map.put("更新者", teamToEnterprise.getUpdateBy());
              map.put("更新时间", teamToEnterprise.getUpdateTime());
              map.put("删除编号", teamToEnterprise.getDeleteId());
              map.put("删除者", teamToEnterprise.getDeleteBy());
              map.put("删除时间", teamToEnterprise.getDeleteTime());
                map.put(" deleteType",  teamToEnterprise.getDeleteType());
              map.put("版本", teamToEnterprise.getEditionName());
              map.put("版本号", teamToEnterprise.getEdition());
                map.put(" fileEncode",  teamToEnterprise.getFileEncode());
              map.put("文件的MD5", teamToEnterprise.getFileMd5());
                map.put(" parentFile",  teamToEnterprise.getParentFile());
                map.put(" effectiveDate",  teamToEnterprise.getEffectiveDate());
                map.put(" expirationDate",  teamToEnterprise.getExpirationDate());
              map.put("项目模板名称", teamToEnterprise.getTemplateName());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
